package com.bstek.datasource.action;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.bstek.common.config.DataSourceConfig;
import com.bstek.common.utils.MultipleJdbcTemplate;
import com.bstek.datasource.bean.DataResult;
import com.bstek.datasource.bean.DataSourceInfo;
import com.bstek.datasource.bean.DataSourceVO;
import com.bstek.ureport.build.Dataset;
import com.bstek.ureport.definition.dataset.Field;
import com.bstek.ureport.definition.dataset.SqlDatasetDefinition;

/**
 * 数据源配置
 * 
 * @author tomcat
 *
 */
@RestController
@RequestMapping("/datasource")
public class DataSourceInfoAction {
	
	@Resource
	private DataSourceConfig dataSourceConfig;
	
	@RequestMapping("/list")
	public List<DataSourceVO> listDruid(@RequestBody DataSourceInfo dto) {
		List<DataSourceVO> result = new ArrayList<DataSourceVO>();
		List<DataSourceInfo> list = dataSourceConfig.getDatasource();
		if(list != null && list.size() > 0) {
			for (DataSourceInfo ds : list) {
				DataSourceVO vo = new DataSourceVO();
				vo.setCode(ds.getCode());
				vo.setName(ds.getName());
				result.add(vo);
			}
		}
		return result;
	}

	@RequestMapping("/tableList")
	public List<Map<String, String>> selectTableList(String dataSourceCode) {
		return MultipleJdbcTemplate.getDatabaseTables(dataSourceCode);
	}

	@RequestMapping("/tableFieldList")
	public List<Field> selectTableFieldList(@RequestBody SqlDatasetDefinition sqlDatasetDefinition) {
		Map<String, Object> params = new HashMap<String, Object>();
		return sqlDatasetDefinition.buildFields(params);
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/preview")
	public DataResult previewData(@RequestBody SqlDatasetDefinition sqlDatasetDefinition) {
		DataResult result = new DataResult();
		String dataSourceCode = sqlDatasetDefinition.getDataSourceCode();
		Connection conn = MultipleJdbcTemplate.buildConnection(dataSourceCode);
		Map<String, Object> params = new HashMap<>();
		List<String> fields = new ArrayList<String>();
		Dataset dataset = null;
		try {
			dataset = sqlDatasetDefinition.buildDataset(params, conn);
		} catch (Exception e) {
			String message = e.getMessage();
			result.setMessage(message.substring(message.indexOf(":")));
		}
		String sql = sqlDatasetDefinition.parseSql(params);
		result.setSql(sql);
		List<Map<String, Object>> data = null;
		if (dataset != null) {
			data = (List<Map<String, Object>>) dataset.getData();
			if (data != null && data.size() > 0) {
				Map<String, Object> item = (Map<String, Object>) data.get(0);
				for (String name : item.keySet()) {
					fields.add(name);
				}
			}
		}
		result.setFields(fields);
		result.setData(data);
		return result;
	}
}
